<?php
namespace app\api\service;
use function PHPSTORM_META\type;
use think\Controller;
use think\Db;
use think\Exception;
use think\Session;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/26 0026
 * Time: 15:40
 */

class Activity extends Controller {

    /**
     * 获取我的活动列表
     * @param $param
     * @return mixed
     */
    public static function get_activity_list($param) {
        try {
            // $param['type']  1 申请中；  2 进行中；  3参与过；  4我发起的；
            $where['member_id'] = $param['member_id'];

            // 初始化返回數據
            $data = [
                'list' => [],
                'is_more' => 0
            ];
            if ($param['type'] == 4) {
                // 我发起的
                $list = model('activity')->where($where)->order('id desc')->paginate();
                if ($list) {
                    foreach ($list as $k => $v) {
                        $data['list'][] = [
                            'name' => $v->name,
                            'address' => $v->address,
                            'is_aa' => $v->is_aa == 1 ? 'AA制' : '发起者买单',
                            'time_remaining' => time() < $v->start_time ? stime($v->start_time - time()) : ($v->status == 3 ? '已结束' :'正在进行'),
                            'start_time' => $v->start_time,
                            'status' => get_activity_status($v->status, $v->start_time),
                            'image' => get_img_url($v->image_1),
                            'id' => $v->id,
                            'application_time' => $v->create_time,
                            'is_group_chat' => $v->is_group_chat,
                            'group_id' => $v->group_id,
                            'type' => $param['type'],
                            'pay_time' => $v->pay_time
                        ];
                    }
                    $list = $list->toArray();
                    $is_more = $list['total'] - ($list['current_page'] * $list['per_page']);
                    $data['is_more'] = $is_more;
                }
            } else {
                // 我申请的
                if ($param['type'] == 1) { // 申请中
                    $where['status'] = 1;
                } else if ($param['type'] == 2) {  // 进行中
                    $where['status'] = 2;
                } else if ($param['type'] == 3) {  // 参与过
                    $where['status'] = 4;
                }

                $activity_participation = model('activity_participation')->where($where)->order('id desc')->paginate();

                if ($activity_participation) {
                    foreach ($activity_participation as $k => $v) {
                        $data['list'][] = [
                            'name' => $v->activity->name,
                            'address' => $v->activity->address,
                            'is_aa' => $v->activity->is_aa == 1 ? 'AA制' : '发起者买单',
                            'time_remaining' => time() < $v->activity->start_time ? stime($v->activity->start_time - time()) : ($v->status == 4 ? '已结束' :'正在进行'),
                            'start_time' => $v->activity->start_time,
                            'application_time' => $v->create_time,
                            'image' => get_img_url($v->activity->image_1),
                            'status' => get_activity_participation_status($v->status),
                            'id' => $v->activity_id,
                            'is_group_chat' => $v->activity->is_group_chat,
                            'group_id' => $v->activity->group_id,
                            'type' => $param['type'],
                            'pay_time' => $v->activity->pay_time
                        ];
                    }
                    $activity_participation = $activity_participation->toArray();
                    $is_more = $activity_participation['total'] - ($activity_participation['current_page'] * $activity_participation['per_page']);
                    $data['is_more'] = $is_more;
                }
            }

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取活动详情
     * @param $param
     * @return array
     */
    public static function get_activity_info($param) {
        Db::startTrans();
        try{
            $activity = model('activity')->get(['id' => $param['id']]);
            $time_remaining = '';
            if ($activity->status != 3) {
                if (time() < $activity->start_time) {
                    $time_remaining = '距离活动开始：' . stime($activity->start_time - time());
                } else {
                    if (($activity->start_time + 24 * 60 * 60) > time()) {
                        $time_remaining = '距离活动结束：' . stime(($activity->start_time + 24 * 60 * 60) - time());
                    } else {
                        // 活动已结束
                        model('activity')->save(['status' => 3], ['id' => $param['id']]);
                        $activity->status = 3; // 更新活动数据状态
                        // 修改活动参与者记录状态
                        model('activity_participation')->save(['status' => 4], ['activity_id' => $param['id']]);
                        // 返还赞助商品押金 返还条件（活动实际参与人数要大于等于赞助商品的规定人数）
                        if ($activity->product && $activity->num >= $activity->product->sponsor_num) {
                            model('member')->where('id', $activity->member_id)->setInc('money', $activity->product->price);
                        }

                        // 返还保证金
                        model('member')->where('id', $activity->member_id)->setInc('money', $activity->price);

                        MemberBill::add_member_bill($activity->member_id, $activity->price, '活动保证金返还', 5, '', '', '系统返还');
                    }
                }
            }

            $image = $activity->product ? $activity->product->images()->where('is_main', 1)->find() : '';

            $data = [
                'name' => $activity->name,
                'address' => $activity->address,
                'is_aa' => $activity->is_aa == 1 ? 'AA制' : '发起者买单',
                'time_remaining' => $time_remaining,
                'start_time' => $activity->start_time,
                'schedule' => get_activity_status_schedule($activity->status, $activity->start_time),
                'status' => get_activity_status($activity->status, $activity->start_time),
                'msg' => $activity->msg,
                'population' => $activity->population,
                'num' => $activity->num,
                'lat' => $activity->lat,
                'lng' => $activity->lng,
                'images' => [
                    get_img_url($activity->image_1),get_img_url($activity->image_2),get_img_url($activity->image_3)
                ],
                'id' => $activity->id,
                'application_time' => time_tran($activity->create_time),
                'nickname' => $activity->orderMember->memberRoleInfo->nickname,
                'headimgurl' => get_img_url($activity->orderMember->memberRoleInfo->headimgurl),
                'product_name' => $activity->product ? $activity->product->name : '',
                'sponsor_num' => $activity->product ? $activity->product->sponsor_num : '',
                'product_image' => $image ? get_img_url($image->thumb) : '',
                'pay_time' => $activity->pay_time,
            ];

            if ($activity->member_id == $param['member_id']) {
                $data['member_status'] = '发起者';
            } else {
                $data['member_status'] = '未申请';
                $member = $activity->activityParticipation()->where('member_id', $param['member_id'])->find();
                if ($member) {
                    $data['member_status'] = get_activity_participation_status($member->status);
                    $data['member_registration'] = $member->registration;
                }
            }
            Db::commit();
            return api_return(200, $data);
        }catch (\Exception $e) {
            Db::rollback();
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取用户未参与的活动列表  热门  附近等
     * @param $param
     * @return array
     */
    public static function get_activity_list_bu_where($param) {
        try{
            if ($param['type'] == 'new') {
                // 最新活动  // 可以是正在进行和已结束的
                $list = model('activity')->where('status', 'neq', 1)->order('id desc')->paginate();
            } else if ($param['type'] == 'nearby') {
                // 根据用户经纬度 获取附近活动  // 必须是能参与的
                $coord = getAround($param['lat'], $param['lng'], 10000);
                $where['lat'] = ['between', [$coord[0], $coord[1]]];
                $where['lng'] = ['between', [$coord[2], $coord[3]]];
                $where['status'] = ['eq', 2];
                $list = model('activity')->where($where)->order('id asc')->select();
            } else {
                throw new \Exception('数据类型错误');
            }

            // 初始化返回數據
            $data = [
                'list' => [],
                'is_more' => 0
            ];

            if ($list) {
                foreach ($list as $k => $v) {
                    $data['list'][] = [
                        'name' => $v->name,
                        'address' => $v->address,
                        'is_aa' => $v->is_aa == 1 ? 'AA制' : '发起者买单',
                        'application_time' => time_tran($v->create_time),
                        'image' => get_img_url($v->image_1),
                        'my_activity' => $v->member_id == $param['member_id'] ? '我发起的' : '',
                        'status' => get_activity_status($v->status, $v->start_time),
                        'id' => $v->id,
                        'lat' => $v->lat,
                        'lng' => $v->lng,
                        'nickname' => $v->orderMember->memberRoleInfo->nickname,
                        'headimgurl' => get_img_url($v->orderMember->memberRoleInfo->headimgurl)
                    ];
                }
                if ($param['type'] == 'new') {
                    $list = $list->toArray();
                    $is_more = $list['total'] - ($list['current_page'] * $list['per_page']);
                    $data['is_more'] = $is_more;
                }
            }

            return api_return(200, $data);
        }catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 申请参加活动
     * @param $param
     * @return array
     */
    public static function participate_activity($param) {
        try{
            $activity = model('activity')->get(['id' => $param['id']]);
            if (!$activity) {
                throw new \Exception('活动不存在！');
            }
            if ($activity->status != 2) {
                throw new \Exception('活动状态异常！');
            }
            if ($activity['num'] >= $activity['population']) {
                throw new \Exception('本活动参与人数已满！');
            }
            $activity_participation = model('activity_participation')->get(['activity_id' => $param['id'], 'member_id' => $param['member_id']]);

            if ($activity_participation && $activity_participation->status == 4) {
                throw new \Exception('活动已结束！');
            }

            if ($activity_participation && $activity_participation->status != 3) {
                throw new \Exception('请勿重复提交申请！');
            }

            if(!$activity_participation) {
                $data = [
                    'activity_id' => $activity->id,
                    'member_id' => $param['member_id'],
                ];
                model('activity_participation')->save($data);
            } else {
                $activity_participation->save(['status' => 1]);
            }


            return api_return(200, []);
        }catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }


    /**
     * 退出活动
     * @param $param
     * @return array
     */
    public static function quit_activity($param) {
        Db::startTrans();
        try{
            $data = [
                'activity_id' => $param['id'],
                'member_id' => $param['member_id'],
            ];
            $activity_participation = model('activity_participation')->get($data);
            if(!$activity_participation) {
                throw new \Exception('你还没有参加这个活动！');
            }

            $activity_participation->delete();

            if ($activity_participation->status == 2) {
                model('activity')->where('id', '=', $param['id'])->setDec('num');
            }

            Db::commit();
            return api_return(200, []);
        }catch (\Exception $e) {
            Db::rollback();
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 设置活动讨论组ID
     * @param $param
     * @return array
     */
    public static function save_activity_discussion_id($param) {
        try{
            $activity = model('activity')->get(['id' => $param['id'], 'member_id' => $param['member_id']]);
            if (!$activity) {
                throw new \Exception('活动不存在！');
            }
            if ($activity['discussion_id']) {
                throw new \Exception('讨论组已存在！');
            }

            model('activity')->save(['discussion_id' => $param['discussion_id']], ['id' => $param['id']]);

            return api_return(200, []);
        }catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取活动用户列表
     * @param $param
     * @return array
     */
    public static function get_activity_member($param) {
        try{
            $activity_participation_member = model('activity_participation')->get(['activity_id' => $param['id'], 'member_id' => $param['member_id']]);
            $activity = model('activity')->get(['id' => $param['id'], 'member_id' => $param['member_id']]);
            if (!$activity_participation_member && !$activity) {
                throw new \Exception('您没有参本活动！');
            }
            $where['activity_id'] = $param['id'];
            $where['status'] = $param['status'];

            if (!$activity && $param['status'] != 2) {
                $where['status'] = 2;
            }

            $activity_participation = model('activity_participation')->where($where)->order('id desc')->paginate();
            $data = [
                'list' => [],
                'is_more' => 0
            ];
            if (count($activity_participation)) {
                foreach ($activity_participation as $v) {
                    $data['list'][] = [
                        'id' => $v->id,
                        'headimgurl' => get_img_url($v->activityParticipationMember->memberRoleInfo->headimgurl),
                        'nickname' => $v->activityParticipationMember->memberRoleInfo->nickname,
                        'status' => $v->status,
                        'create_time' => $v->create_time
                    ];
                }
                $list = $activity_participation->toArray();
                $is_more = $list['total'] - ($list['current_page'] * $list['per_page']);
                $data['is_more'] = $is_more;
            }
            return api_return(200, $data);
        }catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 修改活动申请用户状态
     * @param $param
     * @return array
     */
    public static function edit_member_status($param) {
        Db::startTrans();
        try{
            $activity_participation = model('activity_participation')->get(['id' => $param['id']]);
            if (!$activity_participation) {
                throw new \Exception('参数错误！');
            }

            if ($activity_participation->activity->member_id != $param['member_id']) {
                throw new \Exception('您不是活动发起者！');
            }

            if ($activity_participation->activity->num >= $activity_participation->activity->population) {
                throw new \Exception('活动参与人数已达上限！');
            }
            model('activity_participation')->save(['status' => $param['status']], ['id' => $param['id']]);

            if ($param['status'] == 2) {
                // 如果是通过审核 执行以下操作
                // 1.增加活动参与人数
                model('activity')->where(['id' => $activity_participation->activity_id])->setInc('num');
                // 2.将被审核用户加入群组，如果该活动还没有创建群组，则先创建群组
                Rong::create_group(['id' => $activity_participation->activity_id]);
                $activity = model('activity')->get(['id' => $activity_participation->activity_id]);
                Rong::join_group(['userId' => $activity_participation->member_id,
                    'groupId' => $activity->group_id,
                    'groupName' => $activity->name,
                    'member_id' => $activity_participation->member_id
                ]);
                // 添加群组记录
                $friend_data = [
                    'user_id' => $param['member_id'],
                    'target_id' => $activity_participation->activity_id,
                    'type' => 'group',
                    'group' => 'friend',
                    'update_time' => time(),
                ];
                model('rong_member_friend')->save($friend_data);
                // 更新缓存
                $friends = model('rong_member_friend')->where('user_id', $param['member_id'])->where('type', 'group')->column('target_id');
                $friends = implode(',', $friends);
                cache('friends_group_' . $param['member_id'], $friends);
            }
            Db::commit();
            return api_return(200, []);
        }catch (\Exception $e) {
            Db::rollback();
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取活动群聊信息
     * @param $param
     * @return array
     */
    public static function get_group_chat_info($param) {
        try{
            // 检查当前用户是否参与该活动
            $activity_participation_member = model('activity_participation')->get(['activity_id' => $param['id'], 'member_id' => $param['member_id']]);
            // 检查当前用户是否该活动发起人
            $activity = model('activity')->get(['id' => $param['id'], 'member_id' => $param['member_id']]);
            if (!$activity_participation_member && !$activity) {
                throw new \Exception('您没有参本活动！');
            }

            if ($activity_participation_member && $activity_participation_member->status != 2) {
                throw new \Exception('您无法加入该群聊，请先申请参加活动或者联系活动管理员！');
            }

            // 根据ID重新获取活动数据
            $activity = model('activity')->get(['id' => $param['id']]);

            $data = [
                'name' => $activity->name,
                'group_id' =>  $activity->group_id
            ];

            return api_return(200, $data);
        }catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取活动群聊用户信息
     * @param $param
     * @return array
     */
    public static function get_activity_group_member($param) {
        try{
            // 检查当前用户是否有加入群聊
            $activity_group_chat_member = model('rong_member_relation')->get(['targetId' => $param['group_id'], 'userId' => 'jx_rong_' . $param['member_id']]);

            if (!$activity_group_chat_member) {
                throw new \Exception('您没有加入本活动群聊！');
            }

            $list = model('rong_member_relation')->all(['targetId' => $param['group_id']]);
            $data = [];
            if ($list) {
                foreach ($list as $v) {
                    $data[] = [
                        'user_id' => $v->userId,
                        'headimgurl' => get_img_url($v->target_headimgurl),
                        'nickname' => $v->target_nickname
                    ];
                }
            }
            return api_return(200, $data);
        }catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 根据群ID获取群聊天记录
     * @param $param
     * @return array
     */
    public static function get_group_chat_data_by_group_id($param) {
        try{
            // 群用户数据
            $group_member = self::get_activity_group_member($param);
            if ($group_member['code'] != 200) {
                throw new \Exception($group_member['msg']);
            }
            $group_member = $group_member['data'];

            $rong_member_info = model('rong_member_info')->get(['member_id' => $param['member_id']]);

            // 获取群聊记录
            $list = model('rong_msg')->all(['targetId' => $param['group_id']]);
            $data = [];
            if ($list) {
                $data = [];
                foreach ($list as $v) {
                    if ($v->userId == $rong_member_info->userId) {
                        $data['list'][] = [
                            'headimgurl' => get_img_url($rong_member_info->portraitUri),
                            'nickname' => $rong_member_info->name,
                            'action' => 'send',
                            'msg' => $v->msg,
                        ];
                    } else {
                        $data['list'][] = [
                            'headimgurl' => $group_member[$v->userId]['headimgurl'],
                            'nickname' => $group_member[$v->userId]['nickname'],
                            'action' => 'accept',
                            'msg' => $v->msg,
                        ];
                    }
                }
            }
            return api_return(200, $data);
        }catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 举报
     * @param $param
     * @return array
     */
    public static function activity_report($param) {
        try{
            $activity = model('activity')->get(['id' => $param['id']]);
            if (!$activity) {
                throw new \Exception('活动不存在！');
            }

            $activity_report = model('activity_report')->get(['activity_id' => $param['id'], 'member_id' => $param['member_id']]);
            if ($activity_report) {
                throw new \Exception('请勿重复举报！');
            }
            $data = [
                'activity_id' => $param['id'],
                'member_id' => $param['member_id'],
                'msg' => $param['msg'],
            ];
            model('activity_report')->save($data);
            return api_return(200, []);
        }catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 活动签到
     * @param $param
     * @return array
     */
    public static function activity_registration($param) {
        try {
            // 获取活动数据
            $activity = model('activity')->get(['id' => $param['id']]);
            if (!$activity) {
                throw new \Exception('活动不存在');
            }

            $activity_member = model('activity_participation')->get(['activity_id' => $param['id'], 'member_id' => $param['member_id']]);

            if (!$activity_member) {
                throw new \Exception('活动参与者才能签到');
            }

            if (time() < $activity->start_time || time() > ($activity->start_time + 60 * 60 * 24)) {
                throw new \Exception('请在活动进行期间签到');
            }

            if ($activity_member->registration) {
                throw new \Exception('请勿重复签到');
            }

            $activity_member->save(['registration' => 1]);

            return api_return(200, []);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }
}